import os
import re
import sys
import shutil
import compileall
from pathlib import Path
from zipfile import ZipFile, ZIP_DEFLATED


py_path = Path("taobao_check")
zip_name = 'taobao_check.zip'


def delete_files(pack, pattern):
    print(f"delete all {pattern} from {pack}.")
    for i in pack.rglob(pattern):
        if i.is_file():
            os.remove(i)
        else:
            shutil.rmtree(i)


def zip_pyc(pyc_path):
    print(f"add pyc files to {zip_name}")
    with ZipFile(zip_name, 'w', compression=ZIP_DEFLATED, compresslevel=6) as myzip:
        for pyc in pyc_path.rglob("*.pyc"):
            arcname = re.sub("_pyc", "", str(pyc))
            myzip.write(pyc, Path(arcname))


def rename_pyc(pyc_path):
    print("rename all pyc files.")
    for pyc in pyc_path.rglob("*.pyc"):
        new_pyc = re.sub("\.cpython-[0-9]{2}\.", ".", str(pyc))
        new_pyc = re.sub(r"\\__pycache__", "", new_pyc)
        pyc.rename(Path(new_pyc))


def backup_config():
    config_path = Path("config")
    backup_path = config_path / "backup"
    if backup_path.exists():
        shutil.rmtree(backup_path)
    shutil.copytree(config_path, backup_path)
    for f in backup_path.rglob("*.json"):
        n = f.with_suffix("")
        f.rename(n)


def gen_release(pack, delete=True):
    # 删除原本的.pyc文件
    delete_files(py_path, "*.pyc")
    # 编译生成 .pyc 文件
    compileall.compile_dir(pack)
    # 将文件夹复制一份
    pyc_path = pack.with_name(f"{pack.name}_pyc")
    if pyc_path.exists():
        shutil.rmtree(pyc_path)
    print(f"copy {pack} to {pyc_path}")
    shutil.copytree(pack, pyc_path)
    # 对.pyc进行重命名
    rename_pyc(pyc_path)
    # 删除多余的文件和文件夹
    delete_files(pyc_path, "*.py")
    delete_files(pyc_path, "__pycache__")
    # 打包
    zip_pyc(pyc_path)
    # 删除临时文件夹
    if delete:
        print(f"remove {pyc_path}")
        shutil.rmtree(pyc_path)


if __name__ == "__main__":
    if len(sys.argv) > 1:
        gen_release(py_path, False)
    else:
        gen_release(py_path)
    backup_config()
